var DatebaseName = 'SYH'
/* 创建数据库 */

const openDatabase = ()=>{
	var isopen = plus.sqlite.isOpenDatabase({
		name:DatebaseName,
		path:"_doc/myh.db"
	});
	let p = new Promise((res,rej)=>{
		if(!isopen){
			plus.sqlite.openDatabase({
				name:DatebaseName,
				path:"_doc/myh.db",
				success: function(e){
					console.log('openDatabase success!');
					res(e)
				},
				fail: function(e){
					console.log('openDatabase failed: '+JSON.stringify(e));
					rej(e)
				}
			});
		}else{
			res()
		}
	})
	return p;
}

/* 关闭数据库 */
const closeDatabase = ()=>{
	let p = new Promise((res,rej)=>{
		plus.sqlite.closeDatabase({
			name:DatebaseName,
			success: function(e){
				console.log('closeDatabase success!');
				res(e)
			},
			fail: function(e){
				console.log('closeDatabase failed: '+JSON.stringify(e));
				rej(e)
			}											
		});
	})
	return p;
}
/* 创建分类表 */
const creatCategoryTable = ()=>{
	let p = new Promise((res,rej)=>{
			plus.sqlite.executeSql({
				name: DatebaseName,
				sql: 'create table if not exists Category (id integer primary key,index_icons text, name text)',
				success: function(e){
					console.log('table success')
					res(e)
				},
				fail: function(e){
					console.log('executeSql failed: '+JSON.stringify(e));
					rej(e)
				}
			});
		})
	return p;
}
/* 创建表 */
const creatTable = (table,args)=>{
	let p = new Promise((res,rej)=>{
		plus.sqlite.executeSql({
			name: DatebaseName,
			sql: 'create table if not exists '+table+' (id integer primary key autoincrement,'+args+')',
			success: function(e){
				res(e)
			},
			fail: function(e){
				console.log('executeSql failed: '+JSON.stringify(e));
				rej(e)
			}
		});
	})
	return p;
}
/* 执行增删改 */
function executeSQL(sql){
	let p = new Promise((res,rej)=>{
		plus.sqlite.executeSql({
			name: DatebaseName,
			sql:sql,
			success: function(e){
				console.log('excuteSql success')
				res(e)
			},
			fail: function(e){
				console.log('executeSql failed: '+JSON.stringify(e));
				rej(e)
			}
		});
	});
	return p;
}
/* 执行查询 */
function selectSql(sql){
	let p = new Promise((res,rej)=>{
		plus.sqlite.selectSql({
			name: DatebaseName,
			sql:sql ,
			success: function(e){
				res(e)
			},
			fail: function(e){
				rej(e)
				// console.log('executeSql failed: '+JSON.stringify(e));
			}
		});
	});
	return p;
}
module.exports = {
	openDatabase,
	closeDatabase,
	creatTable,
	executeSQL,
	selectSql,
	creatCategoryTable
}